var util = require('../../../utils/util.js');
var apiObject = require('../../../utils/api.js');
var app = getApp();
Page({

  data: {
    imageHost: apiObject.imageHost,
    isChangeImage: false,
    user: { headUrl: "head.png" },
    avatarUrl:""
  },

  onLoad: function (options) {
    var that = this;
    util.request(apiObject.api.getUserInfo).then(function (res) {
      console.log(res)
      if (res.code == 200) {
        that.setData({
          user: res.result.user
        })
      } else {
        util.showModal(res.message);
      }
    })
  },



  uploadImage: function (e) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        that.setData({
          isChangeImage: true,
          avatarUrl: res.tempFilePaths[0]
        })
      }
    })
  },
  nicknameInput: function(e) {
    var nickname ="user.nickname"
    this.setData({
      [nickname]: e.detail.value
    })
  },
  submit:function(){
    var that=this;

    if (this.data.isChangeImage){

      util.uploadImage(apiObject.api.alterUserInfo,
        that.data.avatarUrl,{
          nickname: that.data.user.nickname
        }).then(function (res) {
          console.log(res)
          if (res.code == 200) {
            util.showModal("保存成功").then(function(res){
              wx.switchTab({
                url: '../main/index',
              })
            });
          } else {
            util.showModal(res.message);
          }
      })
    }else{
      util.request(apiObject.api.alterUserInfo,{
        nickname:that.data.user.nickname
      }).then(function (res) {
        console.log(res)
        if (res.code == 200) {
          util.showModal("保存成功").then(function (res) {
            wx.switchTab({
              url: '../main/index',
            })
          });
        } else {
          util.showModal(res.message);
        }
      })
    }
  }
})